package it.sebsibenal.server;

import it.sebsibenal.server.dao.UserDAO;
import it.sebsibenal.server.dao.UserGroupDAO;
import it.sebsibenal.shared.User;
import it.sebsibenal.shared.UserGroup;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.docs.DocsService;
import com.googlecode.objectify.Key;

public abstract class BaseService {

	private UserDAO userDAO;
	private UserGroupDAO userGroupDAO;
	private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH.mm.ss");

	protected User getCurrentUser() {
		initTestUsers();
		com.google.appengine.api.users.User currentUser = UserServiceFactory.getUserService().getCurrentUser();
		return userDAO.findByEmail(currentUser.getEmail());
	}

	private void initTestUsers() {
		User user = userDAO.findByEmail("simone.masoni@gmail.com");
		if (user == null) {
			user = new User("Simone", "Masoni", "Maso", "simone.masoni@gmail.com");
			userDAO.insert(user);
		}
		if (userGroupDAO.findByName("sebsibenal")==null) {
			UserGroup ug = new UserGroup();
			ug.setName("sebsibenal");
			ug.setMembers(new Key[]{new Key(User.class, user.getId())});
			userGroupDAO.insert(ug);
		}
	}

	public String getNow() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR_OF_DAY, 2);
		return sdf.format(cal.getTime());
	}
	
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public UserGroupDAO getUserGroupDAO() {
		return userGroupDAO;
	}

	public void setUserGroupDAO(UserGroupDAO userGroupDAO) {
		this.userGroupDAO = userGroupDAO;
	}
	
}
